const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const dayjs = require('dayjs');
const ACTS = 'cloud-activities';
const PART = 'cloud-participant';
const BASE = 'cloud-user-base';
const VLOG = 'cloud-vote-log';
const db = cloud.database();
const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    /**获取当前日期 */
    let nowDate = dayjs().format('YYYY-MM-DD');
    console.log(nowDate)
    /**获取用户openid */
    let openid = event.openid || wxContext.OPENID
    /**获取基础用户信息 */
    let userRes = await db.collection(BASE).where({
        openid
    }).get();
    if (userRes.data.length == 0) {
        return {
            errCode: -1,
            errMsg: '基础用户信息不存在'
        }
    }
    let userData = userRes.data[0];
    /**获取参与信息 */
    //participantId
    let partId = event.partId;
    let partRes = await db.collection(PART).doc(partId).get();
    let partData = partRes.data;
    /**获取当前活动信息 */
    let activityId = partData.activityId;
    let activityRes = await db.collection(ACTS).doc(activityId).get();
    let activityData = activityRes.data;

    /**查询当前活动需要的 */
    let voterId = userData._id;
    let voteRes = null
    /**是否是每日刷新 */
    let dayFresh = activityData.dayFresh;
    if(dayFresh){
        voteRes = await db.collection(VLOG).where({
            activityId,
            voterId,
            _createTime:nowDate
        }).get();
    }else{
        voteRes = await db.collection(VLOG).where({
            activityId,
            voterId
        }).get();
    }
    
    let canVote = true
    let errMsg = ''
    let voteData = voteRes.data;
    voteData.forEach(function(ele,index){
        if(ele.participantId == partId){
            canVote = false
            errMsg = '已经投过了'
        }
    })
    if(voteData.length >= activityData.initTicket){
        canVote = false
        return {
            errCode:-1,
            errMsg:'你没有多余的票了',
            canVote
        }
    }
    if(!canVote){
        return {
            errCode:-1,
            errMsg,
            canVote
        }
    }
    /**新增 */
    db.collection(PART).doc(partId).update({
        data:{
            voteNum:_.inc(1)
        }
    })
    return await db.collection(VLOG).add({
        data:{
            activityId,
            voterAvatar:userData.avatarUrl,
            voterId,
            participantId:partId,
            _createTime:nowDate
        }
    })
}